package com.hontech.bv.conn

import com.hontech.bv.codec.decodeUint8
import com.hontech.bv.codec.toHex
import com.hontech.bv.conn.serial.SerialType
import com.hontech.bv.conn.serial.Uint8
import com.hontech.bv.error.ExecException

class ReadFrame (val buf: ByteArray) {

    val req: Int = decodeUint8(buf, 0)
    val type: Int
    val seq: Int
    val dest: Int
    val src: Int

    init {
        val tmp = decodeUint8(buf, 1)
        type = tmp and 0x0F
        seq = (tmp shr 4) and 0x0F

        val id = decodeUint8(buf, 2)
        dest = id and 0x0F
        src = (id shr 4) and 0x0F
    }

    fun promiseIndex() = (req shl 8) + seq

    private fun ec(): Int {
        val value = Uint8()
        Proto.parse(buf, 3, arrayOf(value))
        return value.value
    }

    fun assert(name: String = "") {
        val ec = ec()
        if (ec != ErrCode.OK) {
            throw ExecException( "$name=>${ErrCode.msg(ec)}" )
        }
    }

    fun parse(args: Array<SerialType>) {
        Proto.parse(buf, 3, args)
    }

    fun info(): String {
        return "${Proto.nameReq(req)} 目标:${Proto.nameId(dest)} 源:${Proto.nameId(src)}"
    }

    override fun toString(): String {
        return "req:${req} dest:${dest} src:${src} seq:${seq} data:${buf.toHex()}"
    }
}

